//
//  TPHomeViewController.m
//  TPHelper
//
//  Created by xuqiang on 2020/7/23.
//  Copyright © 2020 xuqiang. All rights reserved.
//

#import "TPHomeViewController.h"
#import "WIFIHelper.h"
#import "SearchDevicesVC.h"
#import "LocalPicturesVC.h"
#import "LocalVideosVC.h"
#import "TPHelper-Swift.h"
#import "MyCollectionViewCell.h"
#import <Masonry/Masonry.h>
#import "TPPlayerView.h"
#import "TPPlayerManager.h"
#import <GCDWebServer/GCDWebDAVServer.h>
#import "GCDWebServerDataResponse.h"
#import  <GCDWebServer/GCDWebServerFileResponse.h>
#import "UIImage+Compress.h"

@import TZImagePickerController;

@interface TPHomeViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout,SearchDevicesVCDelegate,TPPlayerViewDelegate,GCDWebDAVServerDelegate>
@property (weak, nonatomic) IBOutlet UIView *listBox;
@property (strong, nonatomic) UICollectionView *collectionView;
@property (nonatomic,strong) NSMutableArray *picList;
@property (nonatomic,strong) NSMutableArray *vidioList;
@property (nonatomic,assign) PHAssetMediaType mediaType;
@property (nonatomic,strong) TPPlayerView *playerView;

@property (nonatomic, strong) GCDWebDAVServer* davServer;
@property(nonatomic,strong) MRDLNA *dlnaManager;
@property (nonatomic,strong) NSData *imageData;
@property (nonatomic,strong) NSMutableArray *imageArray;
@property (nonatomic,assign) NSInteger index;
@end

@implementation TPHomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Do any additional setup after loading the view.
    self.title = @"本地投屏";

    [self configCollectionView];
    [self.view addSubview:self.playerView];
    [self.playerView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(0);
        make.bottom.mas_equalTo(@0);
        make.height.mas_equalTo(@50);
    }];
    self.playerView.hidden = YES;
    UIButton *right = [UIButton buttonWithType:UIButtonTypeCustom];
    [right setImage:[UIImage imageNamed:@"btn_search_device"] forState:UIControlStateNormal];
    right.frame = CGRectMake(0, 0, 44, 44);
    [right addTarget:self action:@selector(rightClicked:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:right];
    
}

- (void)configCollectionView {
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.itemSize =CGSizeMake(([UIScreen mainScreen].bounds.size.width-3)*0.25,([UIScreen mainScreen].bounds.size.width-3)*0.25);
    self.collectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:layout];
    self.collectionView.backgroundColor = [UIColor clearColor];
    [self.listBox addSubview:self.collectionView];
    [self.collectionView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(0);
    }];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    [self.collectionView registerClass:[MyCollectionViewCell class] forCellWithReuseIdentifier:@"LocalPicturesVC"];
}

- (void)rightClicked:(id)sender {
    SearchDevicesVC *searchVc = [SearchDevicesVC new];
    searchVc.delegate = self;
    searchVc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:searchVc animated:YES];
}

- (IBAction)buttonTpClicked:(id)sender {
    if (self.picList.count == 0 && self.vidioList.count == 0) {
        [self showToast:@"请选择要投屏的内容"];
        return;
    }
    self.index = 0;
    if (self.mediaType == PHAssetMediaTypeImage) {
        [self makeServer];
    }else if (self.mediaType == PHAssetMediaTypeVideo){
        if (self.davServer.isRunning){
            [self.davServer stop];
        }
        NSArray *allfiles = [self getAllMoviesForLocalShow:self.vidioList];
        [TPPlayerManager sharedTPPlayerManager].localFiles = allfiles;
        [[TPPlayerManager sharedTPPlayerManager] play];
        self.playerView.hidden = NO;
    }

//    SearchDevicesVC *searchVc = [SearchDevicesVC new];
//    if (self.mediaType == PHAssetMediaTypeImage) {
//        searchVc.playType = 0;
//        searchVc.assets = self.picList;
//    }else if (self.mediaType == PHAssetMediaTypeVideo){
//        searchVc.playType = 1;
//        searchVc.assets = self.vidioList;
//    }
//    searchVc.hidesBottomBarWhenPushed = YES;
//    searchVc.delegate = self;
//    [self.navigationController pushViewController:searchVc animated:YES];
}

- (IBAction)buttonVidoClicked:(id)sender {
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:100 delegate:nil];
    imagePickerVc.allowPickingImage = NO;
    imagePickerVc.allowPickingVideo = YES;
    imagePickerVc.allowTakePicture = NO;
    imagePickerVc.allowTakeVideo = NO;
    imagePickerVc.allowPickingMultipleVideo=YES;
    // You can get the photos by block, the same as by delegate.
    // 你可以通过block或者代理，来得到用户选择的照片.
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        //放入列表 分别投屏
        self.mediaType = PHAssetMediaTypeVideo;
        [self.vidioList removeAllObjects];
        [self.vidioList addObjectsFromArray:assets];
        [self.collectionView reloadData];
    }];
    [self presentViewController:imagePickerVc animated:YES completion:nil];
}

- (IBAction)buttonPictureClicked:(id)sender {
//    SearchDevicesVC *searchVc = [SearchDevicesVC new];
//    searchVc.hidesBottomBarWhenPushed = YES;
//    [self.navigationController pushViewController:searchVc animated:YES];
//    LocalPicturesVC *vc = [[LocalPicturesVC alloc]init];
//    [self.navigationController pushViewController:vc animated:YES];
    
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:100 delegate:nil];
    imagePickerVc.allowPickingImage = YES;
    imagePickerVc.allowPickingVideo = NO;
    imagePickerVc.allowTakePicture = NO;
    imagePickerVc.allowTakeVideo = NO;
    imagePickerVc.allowPickingMultipleVideo=YES;
    // You can get the photos by block, the same as by delegate.
    // 你可以通过block或者代理，来得到用户选择的照片.
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        self.imageArray = photos;
        self.mediaType = PHAssetMediaTypeImage;
        //放入列表 分别投屏
        [self.picList removeAllObjects];
        [self.picList addObjectsFromArray:assets];
        [self.collectionView reloadData];
        self.playerView.hidden = YES;
    }];
    [self presentViewController:imagePickerVc animated:YES completion:nil];
}

//开启服务器
-(void)makeServer{
    [[TPPlayerManager sharedTPPlayerManager] endDLNA];
    if (self.davServer.isRunning) {
        [self.davServer stop];
    }
    NSString* documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    self.davServer = [[GCDWebDAVServer alloc] initWithUploadDirectory:documentsPath];
    self.davServer.delegate =  self;
    __weak typeof (self) weakSelf = self;//myImage
    [self.davServer  addHandlerForMethod:@"GET" pathRegex:@"abcde" requestClass:[GCDWebServerRequest class] asyncProcessBlock:^(__kindof GCDWebServerRequest * _Nonnull request, GCDWebServerCompletionBlock  _Nonnull completionBlock) {
        GCDWebServerDataResponse *response = [GCDWebServerDataResponse responseWithData:weakSelf.imageData contentType:@"image/jpeg"];
        completionBlock(response);
    }];
    [self.davServer start];
}

-(void)webServerDidStart:(GCDWebServer *)server{
    if (self.mediaType == PHAssetMediaTypeImage) {
        self.dlnaManager = [MRDLNA sharedMRDLNAManager];
        self.dlnaManager.typeStr = @"1";
        self.dlnaManager.playUrl = [NSString stringWithFormat:@"%@abcde",self.davServer.serverURL.absoluteString];

        UIImage *image = self.imageArray[self.index];
        self.imageData = [image compressWithMaxLength:1024*1024*10];
        [self.dlnaManager playTheURL:self.dlnaManager.playUrl];
        [self.dlnaManager startDLNA];
    }else{
//        self.dlnaManager = [MRDLNA sharedMRDLNAManager];
//        self.dlnaManager.delegate = self;
//        self.dlnaManager.typeStr = @"2";
//        self.dlnaManager.playUrl = [NSString stringWithFormat:@"%@video2",self.davServer.serverURL.absoluteString];
//        [self.dlnaManager startDLNA];
    }
}

#pragma mark - 点击设备返回
- (void)didConnectDevice:(CLUPnPDevice *)device {
    self.navigationItem.title = [NSString stringWithFormat:@"本地投屏(%@)",device.friendlyName];
}

#pragma mark - TPPlayerViewDelegate
- (void)play {
    [[TPPlayerManager sharedTPPlayerManager] play];
}
- (void)start {
    [[TPPlayerManager sharedTPPlayerManager] start];
}
- (void)stop {
    [[TPPlayerManager sharedTPPlayerManager] stop];
    //隐藏掉playerview
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        self.playerView.hidden = YES;
    });
}
- (void)pause {
    [[TPPlayerManager sharedTPPlayerManager] pause];
}
- (void)soundLess {
    [[TPPlayerManager sharedTPPlayerManager] volumeLess];
}
- (void)soundAdd {
    [[TPPlayerManager sharedTPPlayerManager] volumeAdd];
}

#pragma mark -  collectionView
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if (self.mediaType == PHAssetMediaTypeImage) {
        return self.picList.count;
    }else {
        return self.vidioList.count;
    }
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    MyCollectionViewCell *cell =(MyCollectionViewCell*) [collectionView dequeueReusableCellWithReuseIdentifier:@"LocalPicturesVC" forIndexPath:indexPath];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView
       willDisplayCell:(MyCollectionViewCell *)cell
    forItemAtIndexPath:(NSIndexPath *)indexPath {
    if (self.mediaType == PHAssetMediaTypeImage) {
        [cell makeAsset:self.picList[indexPath.row] withSize:CGSizeMake(90, 90) isImage:YES];
    }else{
        [cell makeAsset:self.vidioList[indexPath.row] withSize:CGSizeMake(90, 90) isImage:NO];
    }
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return CGSizeMake(85, 85);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 1;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 1;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    self.index = indexPath.row;
    if (self.mediaType == PHAssetMediaTypeImage) {
        [self makeServer];
    }else if (self.mediaType == PHAssetMediaTypeVideo){
        if (self.davServer.isRunning){
            [self.davServer stop];
        }
        NSArray *allfiles = [self getAllMoviesForLocalShow:@[self.vidioList[indexPath.row]]];
        [TPPlayerManager sharedTPPlayerManager].localFiles = allfiles;
        [[TPPlayerManager sharedTPPlayerManager] play];
        self.playerView.hidden = NO;
    }
    
}
- (NSArray *)getAllMoviesForLocalShow:(NSArray *)assets {
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);

    NSMutableArray* files = [NSMutableArray new];
    [assets enumerateObjectsUsingBlock:^(PHAsset * assert, NSUInteger idx, BOOL * _Nonnull stop) {
        [[PHImageManager defaultManager] requestAVAssetForVideo:assert options:nil resultHandler:^(AVAsset * _Nullable asset, AVAudioMix * _Nullable audioMix, NSDictionary * _Nullable info) {
            if (asset) {
                AVURLAsset *urlAsset = (AVURLAsset *)asset;
                NSURL *url = urlAsset.URL;
                NSString *path = [url path];
                NSDateFormatter* format = [NSDateFormatter new];
                format.dateFormat = @"yyyy-MM-dd hh:mm aa";
                [files addObject:@{@"url" : path?path:@"", @"title" : @"--",@"asset":asset}];
            }
            dispatch_semaphore_signal(semaphore);
        }];
        dispatch_semaphore_wait(semaphore,DISPATCH_TIME_FOREVER);
    }];
    return files;
}
#pragma mark - Getters
- (NSMutableArray *)picList {
    if (!_picList) {
        _picList = [NSMutableArray new];
    }
    return _picList;
}
- (NSMutableArray *)vidioList {
    if (!_vidioList) {
        _vidioList = [NSMutableArray new];
    }
    return _vidioList;
}
- (TPPlayerView *)playerView {
    if (!_playerView) {
        _playerView = [TPPlayerView loadFromNib];
        _playerView.delegate = self;
    }
    return _playerView;
}
@end

